package com.example.food_contract_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.food_contract_system.domain.Agency;
import com.example.food_contract_system.domain.Boss;
import com.example.food_contract_system.domain.SysRegion;
import com.example.food_contract_system.mapper.BossMapper;
import com.example.food_contract_system.mapper.SysRegionMapper;
import com.example.food_contract_system.service.AgencyService;
import com.example.food_contract_system.mapper.AgencyMapper;
import com.example.food_contract_system.util.R;
import com.example.food_contract_system.vo.AddAgencyVo;
import com.example.food_contract_system.vo.AgencyBossVo;
import com.example.food_contract_system.vo.BossUpdateVo;
import com.example.food_contract_system.vo.LoginVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
* @author Lhy
* @description 针对表【agency】的数据库操作Service实现
* @createDate 2023-07-06 09:21:49
*/
@Service
@Slf4j
public class AgencyServiceImpl extends ServiceImpl<AgencyMapper, Agency> implements AgencyService{

    @Autowired
    private AgencyMapper agencyMapper;
    @Autowired
    private BossMapper bossMapper;
    @Autowired
    private SysRegionMapper sysRegionMapper;

    @Override
    public R check(boolean flag, String region) {

        List<String> regionList = new ArrayList<>();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(region);

            JsonNode regionNode = jsonNode.get("region");
            if (regionNode.isArray()) {
                for (JsonNode valueNode : regionNode) {
                    String value = valueNode.asText();
                    regionList.add(value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (regionList.size() > 0){
            Agency agency = agencyMapper.selectOne(new QueryWrapper<Agency>()
                    .eq("a_r_number", regionList.get(0))
                    .eq("a_qx",0)
                    .ne("a_status",2));
            if (agency != null){
                return R.error(500,"抱歉，您所在地区已经有总代理商");
            }
        }

        return R.ok().put("msg","明智的选择!");
    }

    @Override
    public R addAgency(AddAgencyVo addAgencyVo) {
        if (addAgencyVo != null){
            Agency agency = new Agency();

            UUID uuid = UUID.randomUUID();
            String s = uuid.toString();
            agency.setAId(s.substring(0,4));
            agency.setAAccount(addAgencyVo.getPhone());
            agency.setAPassword(addAgencyVo.getIdCard().substring(addAgencyVo.getIdCard().length()-5,addAgencyVo.getIdCard().length()-1));
            agency.setAName(addAgencyVo.getName());
            agency.setAIdCard(addAgencyVo.getIdCard());
            agency.setAPicture("http://localhost:8081/index/"+addAgencyVo.getImg());
            agency.setAStatus("0");
            if (addAgencyVo.getDelivery()){
                //是true，则是总代理商
                agency.setAQx(0);
                agency.setARNumber(addAgencyVo.getRegion().get(0));
            }else{
                //否则，是代理商
                agency.setAQx(1);
                agency.setARNumber(addAgencyVo.getRegion().get(addAgencyVo.getRegion().size()-1));
                // 获取父级代理商的id
                Agency aRNumber = agencyMapper.selectOne(new QueryWrapper<Agency>()
                        .eq("a_r_number", addAgencyVo.getRegion().get(0)));
                if (aRNumber != null){
                    agency.setAParentId(aRNumber.getAId());
                }else{
                    return R.error(500,"请联系管理员!");
                }
            }

            int insert = agencyMapper.insert(agency);

            if (insert != 0){
                return R.ok().put("msg","成功");
            }
        }
        return R.error();
    }

    @Override
    public R login(LoginVo loginVo) {
        //首先对厂商进行判断
        if (loginVo.getStatus().equals("2")){
            Boss boss = bossMapper.selectOne(new QueryWrapper<Boss>()
                    .eq("b_account", loginVo.getAccount())
                    .eq("b_password", loginVo.getPassword())
                    .eq("b_status", '2'));
            if (boss != null){
                return R.ok().put("msg","登陆成功!").put("data",boss).put("identity","boss");
            }else{
                return R.error().put("msg","请检查账号或密码!");
            }
        }
        if (loginVo.getStatus().equals("0")){
            return getR(loginVo);
        }
        if (loginVo.getStatus().equals("1")){
            return getR(loginVo);
        }
        return R.error(500,"请联系管理员!");
    }

    @Override
    public R getAgencyByBossAgency(String aId) {
        List<Agency> parentId = agencyMapper.selectList(new QueryWrapper<Agency>()
                .eq("a_parent_id", aId));
        List<AgencyBossVo> agencyBossVos = new ArrayList<>();
        if (parentId.size() > 0){
            for (Agency agency : parentId) {
                AgencyBossVo agencyBossVo = new AgencyBossVo();
                agencyBossVo.setAAccount(agency.getAAccount());
                agencyBossVo.setAId(agency.getAId());
                agencyBossVo.setAName(agency.getAName());
                agencyBossVo.setAAccountStatus(agency.getAAccountStatus());
                agencyBossVo.setAPicture(agency.getAPicture());
                agencyBossVo.setAStatus(agency.getAStatus());

                SysRegion sysRegion = sysRegionMapper.selectOne(new QueryWrapper<SysRegion>()
                        .eq("region_id", agency.getARNumber()));

                agencyBossVo.setRegionName(sysRegion.getRegionName());

                agencyBossVos.add(agencyBossVo);
            }
        }

        return R.ok().put("data",agencyBossVos);
    }

    @Override
    public R getAgencyById(String aId) {
        Agency agency = agencyMapper.selectOne(new QueryWrapper<Agency>()
                .eq("a_id", aId));
        if (agency!=null){
            return R.ok().put("data",agency);
        }
        return R.error();
    }

    @Override
    public R updateAgencyPwd(String aId, BossUpdateVo bossUpdateVo) {
        Agency agency = agencyMapper.selectOne(new QueryWrapper<Agency>()
                .eq("a_id", aId));
        if (agency != null){
            if (!bossUpdateVo.getKey().equals(agency.getAPassword())){
                return R.error(500,"您的密码不正确!");
            }else{
                agencyMapper.updateMyself(aId,bossUpdateVo.getValue());
                return R.ok().put("msg","修改成功");
            }
        }
        return R.error();
    }

    private R getR(LoginVo loginVo) {
        Agency agency = agencyMapper.selectOne(new QueryWrapper<Agency>()
                .eq("a_account", loginVo.getAccount())
                .eq("a_password", loginVo.getPassword())
                .eq("a_qx", loginVo.getStatus()));
        if (agency != null){
            if (agency.getAStatus().equals("2")){
                return R.error().put("msg","您的审批被驳回，请联系客服询问");
            }
            return R.ok().put("msg","登陆成功!").put("data",agency);
        }else{
            return R.error().put("msg","请检查账号或密码!");
        }
    }
}




